import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/api/odoo/dynamic_data_api.dart';
import 'package:flutter_admin/api/odoo/purchase_supplier_evaluation_odoo_api.dart';
import 'package:flutter_admin/models/odoo/purchase_supplier_evaluation.dart';
import 'package:flutter_admin/pages/common/cry/cry_button.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_input.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_select.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/pages/common/cry/utils/cry_utils.dart';
import 'package:flutter_admin/pages/common/cry/vo/select_option_vo.dart';
import 'package:flutter_admin/pages/odoo/product_productunitprice/product_list.dart';
import 'package:flutter_admin/pages/odoo/purchase_supplier_evaluation/res_partner.dart';
import 'package:flutter_admin/pages/common/years_date.dart';
import '../../../generated/l10n.dart';

class PurchaseSupplierEvaluationEdit extends StatefulWidget {
  PurchaseSupplierEvaluationEdit({this.purchaseSupplierEvaluation});

  final PurchaseSupplierEvaluation? purchaseSupplierEvaluation;

  @override
  _PurchaseSupplierEvaluationEditState createState() =>
      _PurchaseSupplierEvaluationEditState();
}

class _PurchaseSupplierEvaluationEditState
    extends State<PurchaseSupplierEvaluationEdit> {
  late PurchaseSupplierEvaluation purchaseSupplierEvaluation;
  bool? isAdd;

  final GlobalKey<FormState> formKey = GlobalKey<FormState>();

  //late List<SelectOptionVO> activeList;

  //供应商ID
  List<SelectOptionVO> partnerIdList = [];
  //考评模板ID
  List<SelectOptionVO> templateIdList = [];

  @override
  void initState() {
    super.initState();
    this.isAdd = widget.purchaseSupplierEvaluation == null;
    this.purchaseSupplierEvaluation =
        widget.purchaseSupplierEvaluation ?? PurchaseSupplierEvaluation();
    _loadSelectVO();
  }

  _loadSelectVO() async {
    //考评模板ID
    // templateIdList = await DynamicDataApi.getModelSelect(
    //     model: "purchase.evaluation.template",
    //     name: "template_name",
    //     active: false);

    getTemplateList();
    //activeList=[SelectOptionVO(value:'0',label: "禁用"),SelectOptionVO(value:'1',label: "启用")];
    setState(() {});
  }

  getTemplateList() async {
    var itemList = await DynamicDataApi.getModels(
      model: "purchase.evaluation.item",
    );
    Map projectIdMap = {};
    List projectIdList = [];
    itemList.data.forEach((element) {
      if (element["project_id"] != false) {
        projectIdMap[element["project_id"][0].toString()] = "";
      }
    });
    projectIdMap.keys.forEach((element) {
      projectIdList.add(int.parse(element));
    });
    var productList = await DynamicDataApi.getModels(
        model: "purchase.evaluation.project",
        key: "id",
        operator: "in",
        val: projectIdList);
    Map templateIdMap = {};
    List templateIdList = [];
    productList.data.forEach((element) {
      templateIdMap[element["template_id"][0].toString()] = "";
    });
    templateIdMap.keys.forEach((element) {
      templateIdList.add(int.parse(element));
    });
    var templateList = await DynamicDataApi.getModels(
        model: "purchase.evaluation.template",
        key: "id",
        operator: "in",
        val: templateIdList);
    templateList.data.forEach((element) {
      // templateIdMap[element["template_id"][0].toString()]="";
      this.templateIdList.add(SelectOptionVO(
          value: element["id"].toString(), label: element["template_name"]));
    });
    setState(() {});
  }

  selectResPartner() async {
    showDialog(
      context: context,
      builder: (BuildContext context) => Dialog(
        child: ResPartnerList(),
      ),
    ).then((v) {
      if (v != null) {
        //_query();
        formKey.currentState!.save();

        purchaseSupplierEvaluation.partnerId = v['id'].toString();
        purchaseSupplierEvaluation.partnerName = v['name'];

        setState(() {});
      }
    });
  }

  selectProduct() async {
    showDialog(
      context: context,
      builder: (BuildContext context) => Dialog(
        child: ProductList(),
      ),
    ).then((v) {
      if (v != null) {
        //_query();
        formKey.currentState!.save();
        purchaseSupplierEvaluation.productId = v['id'].toString();
        purchaseSupplierEvaluation.productName = v['name'];
        setState(() {});
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    var form = Form(
      key: formKey,
      child: Wrap(
        children: <Widget>[
          YearsDate(
            context,
            label: '考评月份',
            value: purchaseSupplierEvaluation.evaluationMonth,
            onSaved: (v) {
              purchaseSupplierEvaluation.evaluationMonth = v;
            },
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ),
          CryInput(
            label: '选择供应商',
            value: purchaseSupplierEvaluation.partnerName,
            onSaved: (v) => {purchaseSupplierEvaluation.partnerName = v},
            onTap: () => selectResPartner(),
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ),
          CryInput(
            label: '选择产品',
            value: purchaseSupplierEvaluation.productName,
            onSaved: (v) {
              purchaseSupplierEvaluation.productName = v;
            },
            // onTap: () => selectProduct(),
            // validator: (v) {
            //   return v!.isEmpty ? S.of(context).required : null;
            // },
          ),
          isAdd!
              ? CrySelect(
                  label: '考评模板',
                  dataList: templateIdList,
                  value: purchaseSupplierEvaluation.templateId,
                  onSaved: (v) => {purchaseSupplierEvaluation.templateId = v},
                  validator: (v) {
                    return v!.isEmpty ? S.of(context).required : null;
                  },
                )
              : CryInput(
                  enable: false,
                  label: '考评模板',
                  value: purchaseSupplierEvaluation.templateName,
                ),
          CryInput(
            label: '备注',
            value: purchaseSupplierEvaluation.comment,
            onSaved: (v) {
              purchaseSupplierEvaluation.comment = v;
            },
          ),
        ],
      ),
    );
    var buttonBar = ButtonBar(
      alignment: MainAxisAlignment.center,
      children: <Widget>[
        CryButton(
          label: S.of(context).save,
          onPressed: () {
            FormState form = formKey.currentState!;
            if (!form.validate()) {
              return;
            }
            form.save();
            PurchaseSupplierEvaluationOdooApi.saveOrUpdate(
                    purchaseSupplierEvaluation.toOdooMap())
                .then((ResponseBodyApi res) {
              if (!res.success!) {
                //package:flutter_admin/pages/common/cry(re s.message!);
                return;
              }
              // if(res.data != true && res.data["code"] != "200"){
              //   CryUtils.message(res.data["message"]);
              //   return ;
              // }
              Navigator.pop(context, true);
              CryUtils.message(S.of(context).saved);
            });
          },
          iconData: Icons.save,
        ),
        CryButton(
          label: S.of(context).cancel,
          onPressed: () {
            Navigator.pop(context);
          },
          iconData: Icons.cancel,
        )
      ],
    );
    var result = Scaffold(
      appBar: AppBar(
        title: Text(this.isAdd! ? S.of(context).add : S.of(context).modify),
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [form],
        ),
      ),
      bottomNavigationBar: buttonBar,
    );
    return SizedBox(
      width: 650,
      height: 650,
      child: result,
    );
    // return result;
  }
}
